package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"time"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/tools/clientcmd"
)

func main() {
	ctx := context.Background()
	kubeconfig := flag.String("kubeconfig", "~/.kube/config", "kubeconfig file")
	flag.Parse()
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		fmt.Printf("The kubeconfig cannot be loaded: %v\n", err)
		os.Exit(1)
	}
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		fmt.Printf("Build clientset from config err: %v\n", err)
		os.Exit(1)
	}
	pod, err := clientset.CoreV1().Pods("default").Get(ctx, "api-monitor-0", metav1.GetOptions{})
	if err != nil {
		fmt.Printf("Get pod err: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("%v\n", pod.Labels)

	informerFactory := informers.NewSharedInformerFactory(clientset, time.Second*3)
	podInformer := informerFactory.Core().V1().Pods()
	podInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: func(new interface{}) {},
		UpdateFunc: func(old, new interface{}) {
			fmt.Println("pod update")
		},
		DeleteFunc: func(old interface{}) {},
	})
	informerFactory.Start(wait.NeverStop)
	informerFactory.WaitForCacheSync(wait.NeverStop)

	pod.Labels["test"] = "test"
	clientset.CoreV1().Pods("default").Update(ctx, pod, metav1.UpdateOptions{})
	pod, err = podInformer.Lister().Pods("default").Get("api-monitor-0")
	if err != nil {
		fmt.Printf("Get pod err: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("%v\n", pod.Labels)
	time.Sleep(time.Second * 20)
}
